package com.dd.cloud.user.service.doctor.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.UserConstants;
import com.dd.cloud.user.entity.doctor.DoctorPatientBind;
import com.dd.cloud.user.mapper.doctor.DoctorPatientBindMapper;
import com.dd.cloud.user.service.doctor.IDoctorPatientBindService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author Lx
 * @version 1.0
 */
@Slf4j
@Service
public class DoctorPatientBindServiceImpl extends ServiceImpl<DoctorPatientBindMapper, DoctorPatientBind> implements IDoctorPatientBindService {
    /**
     * 绑定医生患者关系
     *
     * @param doctorId
     * @param medId
     * @param type
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doctorPatientBind(Integer doctorId, String medId, Integer type) {
        QueryWrapper<DoctorPatientBind> qw = new QueryWrapper<>();
        qw.lambda().eq(DoctorPatientBind::getDoctorId, doctorId)
                .eq(DoctorPatientBind::getMedId, medId)
                .eq(DoctorPatientBind::getStatus, UserConstants.DoctorPatientBindStatus.NORMAL);
        int count = count(qw);
        if (count == 0) {
            DoctorPatientBind dpb = new DoctorPatientBind();
            dpb.setDoctorId(doctorId);
            dpb.setMedId(medId);
            dpb.setStatus(UserConstants.DoctorPatientBindStatus.NORMAL);
            dpb.setType(type);
            dpb.setCreateDate(LocalDateTime.now());
            save(dpb);
        }
    }

    /**
     * 修改绑定医生患者关系状态
     *
     * @param doctorId
     * @param medId
     * @param status
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDoctorPatientBind(Integer doctorId, String medId, Integer status) {
        QueryWrapper<DoctorPatientBind> qw = new QueryWrapper<>();
        qw.lambda().eq(DoctorPatientBind::getDoctorId, doctorId)
                .eq(DoctorPatientBind::getMedId, medId)
                .eq(DoctorPatientBind::getStatus, UserConstants.DoctorPatientBindStatus.NORMAL);
        DoctorPatientBind dpb = getOne(qw);
        if (dpb == null) {
            return;
        }
        DoctorPatientBind update = new DoctorPatientBind();
        update.setId(dpb.getId());
        update.setStatus(status);
        updateById(update);
    }
}
